package com.cysd.ewmxns.utils

import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.widget.Toast


import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream

import java.io.File
import java.io.FileInputStream
import java.io.IOException
import kotlin.math.max

object ImageUtil {
     fun uriToImageFile(uri: Uri,mContent:Context): File? {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // 使用MediaStore直接读取（参考网页5）
            val projection = arrayOf(MediaStore.Images.Media.DATA)
            mContent.contentResolver.query(uri, projection, null, null, null)?.use { cursor ->
                if (cursor.moveToFirst()) {
                    File(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)))
                } else null
            }
        } else {
            // 通过文件路径处理
            uri.path?.let { File(it) }
        }
    }
    fun saveQRCodeToGallery(
        context: Context,
        originalBitmap: Bitmap,
        fileName: String = "QR_${System.currentTimeMillis()}.png"
    ) {
        Log.d("QRCodeSaver", "Saving QR code to gallery as: $fileName")

        try {
            // 1. 确保二维码有足够的尺寸和清晰度
            val minSize = 800 // 最小尺寸设为800x800
            val targetSize = max(minSize, max(originalBitmap.width, originalBitmap.height))

            // 2. 创建高质量的大尺寸二维码
            val scaledBitmap = if (originalBitmap.width < targetSize || originalBitmap.height < targetSize) {
                Bitmap.createScaledBitmap(
                    originalBitmap,
                    targetSize,
                    targetSize,
                    true // 使用双线性插值，保持清晰度
                )
            } else {
                originalBitmap
            }

            // 3. 添加白色背景确保二维码清晰可见
            val finalBitmap = addWhiteBackground(scaledBitmap)

            // 4. 保存到相册
            val values = ContentValues().apply {
                put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
                put(MediaStore.Images.Media.MIME_TYPE, "image/png")
                put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES)
            }

            val resolver = context.contentResolver
            val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
                ?: throw IllegalStateException("Failed to create new MediaStore record")

            resolver.openOutputStream(uri)?.use { outputStream ->
                // 使用PNG格式，100质量，确保无损压缩
                if (!finalBitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)) {
                    throw IOException("Failed to compress bitmap")
                }
                outputStream.flush() // 确保数据写入
            }

            // 5. 通知媒体库更新
            context.sendBroadcast(
                Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri)
            )

            Log.d("QRCodeSaver", "QR code saved successfully at: $uri")
            Log.d("QRCodeSaver", "Final bitmap size: ${finalBitmap.width}x${finalBitmap.height}")
            Toast.makeText(context, "二维码保存成功", Toast.LENGTH_SHORT).show()

            // 6. 清理资源
            if (scaledBitmap != originalBitmap) {
                scaledBitmap.recycle()
            }
            if (finalBitmap != scaledBitmap) {
                finalBitmap.recycle()
            }

        } catch (e: Exception) {
            Log.e("QRCodeSaver", "Failed to save QR code", e)
            Toast.makeText(context, "保存失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    /**
     * 为二维码添加白色背景，确保在任何背景下都能清晰识别
     */
    private fun addWhiteBackground(bitmap: Bitmap): Bitmap {
        // 创建带白色背景的新位图
        val resultBitmap = Bitmap.createBitmap(
            bitmap.width + 40, // 左右各加20px边距
            bitmap.height + 40, // 上下各加20px边距
            Bitmap.Config.ARGB_8888
        )

        val canvas = Canvas(resultBitmap)

        // 绘制白色背景
        val backgroundPaint = Paint().apply {
            color = Color.WHITE
            isAntiAlias = true
        }
        canvas.drawRect(0f, 0f, resultBitmap.width.toFloat(), resultBitmap.height.toFloat(), backgroundPaint)

        // 在中心绘制二维码
        canvas.drawBitmap(bitmap, 20f, 20f, null)

        return resultBitmap
    }

    /**
     * 替代方案：使用更高质量的保存方法
     */
    fun saveQRCodeToGalleryHighQuality(
        context: Context,
        originalBitmap: Bitmap,
        fileName: String = "QR_${System.currentTimeMillis()}.png"
    ) {
        Log.d("QRCodeSaver", "Saving QR code with high quality as: $fileName")

        try {
            // 1. 确保二维码尺寸足够大且清晰
            val targetSize = 1200 // 使用1024x1024确保高质量

            val scaledBitmap = Bitmap.createScaledBitmap(
                originalBitmap,
                targetSize,
                targetSize,
                true
            )

            // 2. 转换为字节数组以确保质量
            val byteArrayOutputStream = ByteArrayOutputStream()
            scaledBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream)
            val byteArray = byteArrayOutputStream.toByteArray()

            // 3. 保存到相册
            val values = ContentValues().apply {
                put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
                put(MediaStore.Images.Media.MIME_TYPE, "image/png")
                put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES)
            }

            val resolver = context.contentResolver
            val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
                ?: throw IllegalStateException("Failed to create new MediaStore record")

            resolver.openOutputStream(uri)?.use { outputStream ->
                outputStream.write(byteArray)
                outputStream.flush()
            }

            // 4. 通知媒体库更新
            context.sendBroadcast(
                Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri)
            )

            Log.d("QRCodeSaver", "High quality QR code saved successfully at: $uri")
            Toast.makeText(context, "二维码保存成功", Toast.LENGTH_SHORT).show()

            // 5. 清理资源
            scaledBitmap.recycle()
            byteArrayOutputStream.close()

        } catch (e: Exception) {
            Log.e("QRCodeSaver", "Failed to save QR code", e)
            Toast.makeText(context, "保存失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    /**
     * 将应用图标保存到相册
     */
    public suspend fun saveIconToGallery(

        context: Context,
        iconBytes: ByteArray,
        displayName: String
    ): Uri? = withContext(Dispatchers.IO) {
        try {
            // 添加时间戳避免重复
            val timestamp = System.currentTimeMillis()
            val fileName = "${sanitizeFileName(displayName)}_$timestamp.png"

            val contentValues = ContentValues().apply {
                put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
                put(MediaStore.Images.Media.MIME_TYPE, "image/png")
                put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + "/AppIcons")
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    put(MediaStore.Images.Media.IS_PENDING, 1)
                }
            }

            val resolver = context.contentResolver
            val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)

            uri?.let {
                resolver.openOutputStream(it)?.use { output ->
                    output.write(iconBytes)
                }

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    contentValues.clear()
                    contentValues.put(MediaStore.Images.Media.IS_PENDING, 0)
                    resolver.update(uri, contentValues, null, null)
                }

                // 通知系统相册刷新
                val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
                mediaScanIntent.data = uri
                context.sendBroadcast(mediaScanIntent)

                return@withContext uri
            }
        } catch (e: Exception) {
            Log.e("SaveIcon", "Error saving app icon", e)
        }

        return@withContext null
    }
    // 辅助函数：清理非法文件名字符
    private fun sanitizeFileName(name: String): String {
        return name.replace("[^a-zA-Z0-9_\\-]".toRegex(), "_")
    }
}